<template>
	<view class="login-container">
		<!-- 顶部导航栏 -->
		<view class="navbar">
			<view class="navbar-left" @click="goBack">
				<u-icon name="arrow-left" size="20" color="#333"></u-icon>
			</view>
			<view class="navbar-title">用户登录</view>
			<view class="navbar-right">
				<u-icon name="more-dot-fill" size="20" color="#999"></u-icon>
			</view>
		</view>

		<!-- 主要内容区域 -->
		<view class="main-content">
			<!-- Logo区域 -->
			<view class="logo-section">
				<view class="logo-wrapper">
					<view class="logo-icon">
						<text class="logo-text">H</text>
					</view>
				</view>
			</view>
			
			<u--form labelPosition="left">
				<u-form-item label="账号" prop="userInfo.nickname" borderBottom ref="item1">
					<u--input v-model="userInfo.nickname" border="none"></u--input>
				</u-form-item>
				<u-form-item label="密码" prop="userInfo.password" borderBottom ref="item1">
					<u--input v-model="userInfo.password" type="password" border="none"></u--input>
				</u-form-item>
				<!-- <u-form-item label="验证码" prop="userInfo.code" borderBottom ref="item2">
					<u--input v-model="userInfo.code" border="none" placeholder="请输入验证码" style="flex: 1;"></u--input>
					<image :src="'data:image/jpeg;base64,'+captchaData.img" @click="refreshCaptcha"
						style="width: 100px; height: 40px; margin-left: 10px;" mode="aspectFit"></image>
				</u-form-item> -->
				<u-button text="登录" size="normal" type="primary" @click="toLogin" 
					:custom-style="loginButtonStyle"
					></u-button>
			</u--form>

			<!-- 登录按钮区域 -->
			<!-- <view class="login-section">
				<u-button 
					type="primary" 
					text="手机号极速登录" 
					:custom-style="loginButtonStyle"
					@click="handleQuickLogin"
				></u-button>
			</view> -->

			<!-- 用户协议区域 -->
			<view class="agreement-section">
				<u-checkbox-group v-model="agreementChecked">
					<u-checkbox 
						:name="true"
						shape="circle"
						:custom-style="checkboxStyle"
					></u-checkbox>
				</u-checkbox-group>
				<view class="agreement-text">
					<text class="agreement-desc">若手机号未注册将进入注册流程,注册即视为同意</text>
					<text class="agreement-link" @click="showTerms">《服务条款》</text>
					<text class="agreement-desc">和</text>
					<text class="agreement-link" @click="showPrivacy">《隐私策略》</text>
				</view>
			</view>

			<!-- 其他登录方式 -->
			<view class="other-login-section">
				<view class="divider">
					<view class="divider-line"></view>
					<text class="divider-text">其他登录方式</text>
					<view class="divider-line"></view>
				</view>
				
				<view class="login-methods">
					<view class="method-item" @click="handleMobileLogin">
						<view class="method-icon mobile-icon">
							<u-icon name="phone" size="24" color="#fff"></u-icon>
						</view>
						<text class="method-text">手机验证</text>
					</view>
					
					<view class="method-item" @click="handleAccountLogin">
						<view class="method-icon account-icon">
							<u-icon name="lock" size="24" color="#fff"></u-icon>
						</view>
						<text class="method-text">账号登录</text>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import { userInfo } from 'os';
import {
		get,
		post,
		loginPost
	} from '../../utils/request.js';
	export default {
		data() {
			return {
				agreementChecked: [],
			loginButtonStyle: {
				backgroundColor: '#ff4757',
				borderRadius: '12rpx',
				height: '88rpx',
				fontSize: '32rpx',
				fontWeight: '500'
			},
			checkboxStyle: {
				transform: 'scale(0.8)'
			},
			userId: null,
			userInfo: {
				nickname: "20",
				password: "1111",
				// code: "", // 验证码
				// uuid: "" // 验证码唯一标识
			},
			captchaData: {
				img: "",
				uuid: ""
			}
		}
	},
	onLoad() {
		// 页面加载时获取验证码
		// this.refreshCaptcha();
	},
	methods: {
		// 刷新验证码
		// async refreshCaptcha() {
		// 	try {
		// 		const res = await get(`${this.baseUrl}/captchaImage`);
		// 		if (res.code === 200) {
		// 			this.captchaData = res;
		// 			this.userInfo.uuid = res.uuid; // 更新uuid
		// 		} else {
		// 			uni.showToast({
		// 				title: '获取验证码失败',
		// 				icon: "error"
		// 			});
		// 		}
		// 	} catch (error) {
		// 		uni.showToast({
		// 			title: '获取验证码异常',
		// 			icon: "error"
		// 		});
		// 		console.error("获取验证码失败:", error);
		// 	}
		// },
		async toLogin() {
			// 验证必填项
			if (!this.userInfo.nickname || !this.userInfo.password) {
				uni.showToast({
					title: '请输入用户名和密码',
					icon: "error"
				});
				return;
			}
			
			try {
				uni.showLoading({
					title: '登录中...'
				});
				

				
				// 使用zmhshop的登录接口
				console.log('🔍 发送登录请求...');
				const res = await loginPost('/user1/toLogin', {
					userAccount: this.userInfo.nickname,
					userPassword: this.userInfo.password
				});
				
				console.log('📥 登录响应原始数据:', res);
				console.log('📥 响应类型:', typeof res);
				console.log('📥 响应数据结构:', Object.keys(res || {}));
				

				uni.hideLoading();
				
				// 检查登录响应
				console.log('🔍 检查登录响应...');
				console.log('📋 res存在:', !!res);
				console.log('📋 res.code:', res?.code);
				console.log('📋 res.data存在:', !!res?.data);
				console.log('📋 res.data内容:', res?.data);
				
				if (res && res.code === 200 && res.data) {
					// 登录成功，获取token
					const token = res.data.access_token;
					console.log('🎫 提取的token:', token);
					console.log('🎫 token类型:', typeof token);
					console.log('🎫 token长度:', token ? token.length : 0);
					
					// ========== 控制台输出登录信息 ==========
					console.log('🔐 ========== 登录成功 ==========');
					console.log('📋 登录响应数据:', res);
					console.log('🎫 获取到的Token:', token);
					console.log('🔍 Token长度:', token ? token.length : 0);
					console.log('📅 登录时间:', new Date().toLocaleString());
					console.log('⏰ Token过期时间:', res.data.expires_in);
					
					// 尝试解析JWT Token（仅用于显示，不用于验证）
					if (token) {
						try {
							const tokenParts = token.split('.');
							if (tokenParts.length === 3) {
								const payload = JSON.parse(atob(tokenParts[1]));
								console.log('🔓 Token解析结果:', payload);
								
								console.log('👤 Token中的用户ID:', payload.user_id);
								uni.setStorageSync('userId', payload.user_id);
								console.log('👤 Token中的用户名:', payload.username);
								
							}
						} catch (parseError) {
							console.log('⚠️ Token解析失败:', parseError.message);
						}
					}
					
					// 调用用户信息接口获取用户详情
					try {
						const userInfoRes = await post('/user1/info', {}, {
							header: {
								'Authorization': token  // 直接发送token，不添加"Bearer "前缀
							}
						});
						
						if (userInfoRes && userInfoRes.code === 200 && userInfoRes.data) {
							const userInfo = userInfoRes.data;
							console.log('获取用户信息成功:', userInfo);
							
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});
							
							// 导入认证工具函数
							const { saveLoginInfo, goToHome } = await import('../../utils/auth.js')
							
							// ========== 控制台输出完整用户信息 ==========
							console.log('👤 ========== 用户详细信息 ==========');
							console.log('🆔 用户ID:', userInfo.userId);
							console.log('👤 用户账号:', userInfo.userAccount);
							console.log('📝 用户昵称:', userInfo.userAccount || this.userInfo.nickname);
							console.log('📊 用户状态:', userInfo.userStatus === 1 ? '✅ 正常' : '❌ 禁用');
							console.log('📅 创建时间:', userInfo.createTime);
							console.log('🎫 认证Token:', token);
							
							// 验证token格式
							console.log('🔍 验证token格式...');
							if (token && typeof token === 'string' && token.includes('.')) {
								console.log('✅ Token格式正确，包含JWT分隔符');
							} else {
								console.warn('⚠️ Token格式可能有问题:', token);
							}
							
							// 保存完整的登录信息
							saveLoginInfo({
								userId: userInfo.userId,
								userInfo: {
									userId: userInfo.userId,
									nickname: userInfo.userAccount || this.userInfo.nickname,
									userAccount: userInfo.userAccount,
									userStatus: userInfo.userStatus,
									createTime: userInfo.createTime
								},
								token: token
							});
							

							
							// 直接跳转到首页
							setTimeout(() => {
								goToHome();
							}, 1000);
						} else {
							// 用户信息获取失败，但登录成功
							console.warn('用户信息获取失败:', userInfoRes);
							
							uni.showToast({
								title: '登录成功',
								icon: 'success'
							});
							
							// 导入认证工具函数
							const { saveLoginInfo, goToHome } = await import('../../utils/auth.js')
							
							// 保存基本登录信息
							saveLoginInfo({
								userId: null,
								userInfo: {
									userId: null,
									nickname: this.userInfo.nickname,
									userAccount: this.userInfo.nickname
								},
								token: token
							});
							
							// 直接跳转到首页
							setTimeout(() => {
								goToHome();
							}, 1000);
						}
					} catch (userInfoError) {
						console.error('获取用户信息异常:', userInfoError);
						
						// 用户信息获取失败，但登录成功
						uni.showToast({
							title: '登录成功',
							icon: 'success'
						});
						
						// 导入认证工具函数
						const { saveLoginInfo, goToHome } = await import('../../utils/auth.js')
						
						// 保存基本登录信息
						saveLoginInfo({
							userId: null,
							userInfo: {
								userId: null,
								nickname: this.userInfo.nickname,
								userAccount: this.userInfo.nickname
							},
							token: token
						});
						
						// 直接跳转到首页
						setTimeout(() => {
							goToHome();
						}, 1000);
					}
				} else {
					// 登录失败
					console.error('登录失败:', res);
					
					uni.showToast({
						title: res.msg || '用户名或密码错误',
						icon: "error"
					});
				}
			} catch (error) {
				uni.hideLoading();
				
				console.error('网络请求异常:', error);
				
				// 显示更详细的错误信息
				let errorMsg = '登录请求异常';
				if (error.message) {
					errorMsg = error.message;
				} else if (error.errMsg) {
					errorMsg = error.errMsg;
				}
				
				uni.showToast({
					title: errorMsg,
					icon: "error",
					duration: 3000
				});
			}
		},
		// 返回上一页
		goBack() {
			uni.navigateBack({
				delta: 1
			})
		},
		
		// 手机号极速登录
		handleQuickLogin() {
			if (this.agreementChecked.length === 0) {
				uni.showToast({
					title: '请先同意用户协议',
					icon: 'none'
				})
				return
			}
			
			// 这里可以调用手机号登录接口
			uni.showLoading({
				title: '登录中...'
			})
			
			// 模拟登录请求
			setTimeout(() => {
				uni.hideLoading()
				uni.showToast({
					title: '登录成功',
					icon: 'success'
				})
				// 登录成功后跳转到首页
				setTimeout(() => {
					uni.switchTab({
						url: '/pages/index/index'
					})
				}, 1500)
			}, 2000)
		},
		
		// 手机验证登录
		handleMobileLogin() {
			uni.showToast({
				title: '手机验证登录',
				icon: 'none'
			})
		},
		
		// 账号登录
		handleAccountLogin() {
			uni.showToast({
				title: '账号登录',
				icon: 'none'
			})
		},
		
		// 显示服务条款
		showTerms() {
			uni.showModal({
				title: '服务条款',
				content: '这里是服务条款的详细内容...',
				showCancel: false
			})
		},
		
		// 显示隐私策略
		showPrivacy() {
			uni.showModal({
				title: '隐私策略',
				content: '这里是隐私策略的详细内容...',
				showCancel: false
			})
		},


	}
}
</script>

<style lang="scss" scoped>
.login-container {
	min-height: 100vh;
	background-color: #f8f9fa;
}

.navbar {
	display: flex;
	align-items: center;
	justify-content: space-between;
	padding: 20rpx 30rpx;
	background-color: #fff;
	border-bottom: 1rpx solid #f0f0f0;
	
	.navbar-left, .navbar-right {
		width: 60rpx;
		height: 60rpx;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	
	.navbar-title {
		font-size: 36rpx;
		font-weight: 500;
		color: #333;
	}
}

.main-content {
	padding: 60rpx 40rpx;
}

.logo-section {
	display: flex;
	justify-content: center;
	margin-bottom: 80rpx;
	
	.logo-wrapper {
		.logo-icon {
			width: 120rpx;
			height: 120rpx;
			background: linear-gradient(135deg, #4facfe 0%, #00f2fe 100%);
			border-radius: 24rpx;
			display: flex;
			align-items: center;
			justify-content: center;
			box-shadow: 0 8rpx 24rpx rgba(79, 172, 254, 0.3);
			
			.logo-text {
				color: #fff;
				font-size: 48rpx;
				font-weight: bold;
			}
		}
	}
}

.login-section {
	margin-bottom: 40rpx;
}

.agreement-section {
	display: flex;
	align-items: flex-start;
	margin-bottom: 80rpx;
	padding: 0 20rpx;
	
	.agreement-text {
		flex: 1;
		margin-left: 20rpx;
		line-height: 1.6;
		
		.agreement-desc {
			font-size: 26rpx;
			color: #999;
		}
		
		.agreement-link {
			font-size: 26rpx;
			color: #ff4757;
		}
	}
}

.other-login-section {
	.divider {
		display: flex;
		align-items: center;
		margin-bottom: 60rpx;
		
		.divider-line {
			flex: 1;
			height: 1rpx;
			background-color: #e0e0e0;
		}
		
		.divider-text {
			margin: 0 30rpx;
			font-size: 28rpx;
			color: #999;
		}
	}
	
	.login-methods {
		display: flex;
		justify-content: center;
		gap: 120rpx;
		
		.method-item {
			display: flex;
			flex-direction: column;
			align-items: center;
			
			.method-icon {
				width: 80rpx;
				height: 80rpx;
				border-radius: 50%;
				display: flex;
				align-items: center;
				justify-content: center;
				margin-bottom: 20rpx;
				
				&.mobile-icon {
					background-color: #ff9500;
				}
				
				&.account-icon {
					background-color: #ff4757;
				}
			}
			
			.method-text {
				font-size: 26rpx;
				color: #666;
			}
		}
	}
}
</style> 